package org.sixtythousand.joker.servlet.session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.Serializable;

/**
 * @author zhoulk
 * @date 2023/10/16 17:36
 * @desc
 */
public class SessionData implements Serializable {
    private static final Logger LOG = LoggerFactory.getLogger(SessionData.class);


    protected String id;
    protected long expiry; //precalculated time of expiry in ms since epoch

    protected long accessed;         // the time of the last access
    protected long lastAccessed;     // the time of the last access excluding this one
    protected boolean metaDataDirty; //non-attribute data has changed
    protected long maxInactiveMs;
    protected long cookieSet;

    /**
     * @return time session was accessed
     */
    public long getAccessed() {
        return accessed;
    }

    public void setAccessed(long accessed) {
        this.accessed = accessed;
    }

    /**
     * @return previous time session was accessed
     */
    public long getLastAccessed() {
        return lastAccessed;
    }

    public void setLastAccessed(long lastAccessed) {
        this.lastAccessed = lastAccessed;
    }

    public void calcAndSetExpiry(long time) {
        setExpiry(calcExpiry(time));
        setMetaDataDirty(true);
    }

    public long calcExpiry(long time) {
        return (getMaxInactiveMs() <= 0 ? 0 : (time + getMaxInactiveMs()));
    }

    public long getMaxInactiveMs() {
        return maxInactiveMs;
    }

    public void setExpiry(long expiry) {
        this.expiry = expiry;
    }

    /**
     * @return time at which session expires
     */
    public long getExpiry()
    {
        return expiry;
    }

    /**
     * @param metaDataDirty true means non-attribute data has changed
     */
    public void setMetaDataDirty(boolean metaDataDirty) {
        this.metaDataDirty = metaDataDirty;
    }



    /**
     * @return time cookie was set
     */
    public long getCookieSet()
    {
        return cookieSet;
    }

    public void setCookieSet(long cookieSet)
    {
        this.cookieSet = cookieSet;
    }

    public boolean isExpiredAt(long time)
    {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Testing expiry on session {}: expires at {} now {} maxIdle {}", id, getExpiry(), time, getMaxInactiveMs());

        }
        if (getMaxInactiveMs() <= 0) {
            return false; //never expires
        }

        return (getExpiry() <= time);
    }
}
